package com.bamboo.eduservice.service.impl;

import com.bamboo.commonutils.ResponseEntity;
import com.bamboo.commonutils.ResultCode;
import com.bamboo.eduservice.constant.EduConstant;
import com.bamboo.eduservice.entity.*;
import com.bamboo.eduservice.entity.frontvo.CourseFrontVo;
import com.bamboo.eduservice.entity.frontvo.CourseWebVo;
import com.bamboo.eduservice.entity.vo.CourseInfoVo;
import com.bamboo.eduservice.entity.vo.CoursePublishVo;
import com.bamboo.eduservice.entity.vo.CourseQuery;
import com.bamboo.eduservice.feign.VodFeignClient;
import com.bamboo.eduservice.mapper.EduCourseMapper;
import com.bamboo.eduservice.service.EduChapterService;
import com.bamboo.eduservice.service.EduCourseDescriptionService;
import com.bamboo.eduservice.service.EduCourseService;
import com.bamboo.eduservice.service.EduVideoService;
import com.bamboo.servicebase.exceptionhandler.BambooException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author jack.wu
 * @since 2020-07-05
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Resource
    private EduCourseDescriptionService courseDescriptionService;

    @Resource
    private EduChapterService chapterService;

    @Resource
    private EduVideoService videoService;

    @Resource
    private VodFeignClient vodFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCourseInfo(CourseInfoVo courseInfoVo) {

        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        int insert = baseMapper.insert(course);
        if (insert == 0) {
            throw new BambooException(20001, "添加课程失败");
        }
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        // 建立1对1关系
        courseDescription.setId(course.getId());
        courseDescriptionService.save(courseDescription);
        return course.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoById(String courseId) {
        CourseInfoVo courseInfo = new CourseInfoVo();
        EduCourse course = getById(courseId);
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        // 封装
        BeanUtils.copyProperties(course, courseInfo);
        courseInfo.setDescription(courseDescription.getDescription());
        return courseInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {

        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        int update = baseMapper.updateById(course);
        if (update == 0) {
            throw new BambooException(20001, "修改课程失败");
        }
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(courseInfoVo.getId());
        courseDescriptionService.updateById(courseDescription);
    }

    @Override
    public CoursePublishVo getPublishInfo(String courseId) {
        return baseMapper.getPublishInfoByCourseId(courseId);
    }

    @Override
    public void publish(String courseId) {
        EduCourse course = new EduCourse();
        course.setId(courseId);
        course.setStatus(EduConstant.COURSE_STATUS_NORMAL);
        baseMapper.updateById(course);
    }

    @Override
    public Page<EduCourse> getCourseList(long current, long limit, CourseQuery courseQuery) {

        //创建page对象
        Page<EduCourse> pageCourse = new Page<>(current, limit);
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getTeacherId())) {
            queryWrapper.eq("teacher_id", courseQuery.getTeacherId());
        }
        if (!StringUtils.isEmpty(courseQuery.getTitle())) {
            queryWrapper.like("title", courseQuery.getTitle());
        }
        if (!StringUtils.isEmpty(courseQuery.getStatus())) {
            queryWrapper.eq("status", courseQuery.getStatus());
        }
        if (!StringUtils.isEmpty(courseQuery.getBegin())) {
            queryWrapper.ge("gmt_create", courseQuery.getBegin());
        }
        if (!StringUtils.isEmpty(courseQuery.getEnd())) {
            queryWrapper.le("gmt_create", courseQuery.getEnd());
        }
        queryWrapper.orderByDesc("gmt_create");
        page(pageCourse, queryWrapper);
        return pageCourse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseInfo(String courseId) {
        int delete = baseMapper.deleteById(courseId);
        if (delete <= 0) {
            throw new BambooException(20001, "删除课程失败");
        }
        // 删除视频
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.select("video_source_id");
        List<EduVideo> videoList = videoService.list(wrapper);
        String ids = videoList.stream().map(EduVideo::getVideoSourceId).collect(Collectors.joining(","));
        if (!StringUtils.isEmpty(ids)) {
            ResponseEntity response = vodFeignClient.deleteAlyVideo(ids);
            if (ResultCode.SUCCESS != response.getCode()) {
                throw new BambooException(20001, response.getMessage());
            }
        }
        // 删除小节
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        boolean removeVideo = videoService.remove(videoQueryWrapper);
        if (!removeVideo) {
            throw new BambooException(20001, "删除课程时删除小节失败");
        }
        // 删除章节
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId);
        boolean removeChapter = chapterService.remove(chapterQueryWrapper);
        if (!removeChapter) {
            throw new BambooException(20001, "删除课程时删除章节失败");
        }
        courseDescriptionService.removeById(courseId);
    }

    @Override
    public Map<String, Object> getFrontCourseList(long page, long limit, CourseFrontVo courseFrontVo) {
        Page<EduCourse> coursePage = new Page<>(page, limit);
        //2 根据讲师id查询所讲课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        // 判断条件值是否为空，不为空拼接
        // 一级分类
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        // 二级分类
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        // 关注度
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {
            wrapper.orderByDesc("buy_count");
        }
        // 最新
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {
            wrapper.orderByDesc("gmt_create");
        }
        // 价格
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(coursePage,wrapper);

        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        boolean hasNext = coursePage.hasNext();
        boolean hasPrevious = coursePage.hasPrevious();

        // 把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>(10);
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo getCourseBaseInfo(String id) {
        return baseMapper.selectCourseBaseInfo(id);
    }

}
